package UdpEcho;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private String IP;
    private  int POrt;
    private DatagramSocket socket=null;
    public UdpEchoClient(String ip,int port) throws SocketException {
        this.IP=ip;
        this.POrt=port;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner sc=new Scanner(System.in);
        while(true) {
            if (!sc.hasNext()){
                break;
            }
            System.out.println("请输入您要发送的内容：");
            String request=sc.next();
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(IP),POrt);
            socket.send(requestPacket);
            DatagramPacket responsePacket=new DatagramPacket(new byte[4048],4048);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",8776);
        client.start();
    }
}
